__author__ = 'housne'
import os
import json
import time
import requests
import hashlib
from conf import *
import uuid
import codecs
import re

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STORAGE_PATH = os.path.join(BASE_DIR, BASE_DIR, 'data')
ACCESS_TOKEN_FILE = os.path.join(STORAGE_PATH, 'access_token.json')
JSAPI_TICKET_FILE = os.path.join(STORAGE_PATH, 'jsapi_ticket.json')
DATA_STORAGE_FILE = os.path.join(STORAGE_PATH, 'data.json')

def get_token(url, storage_file, key):
    now = time.time()
    try:
        with open(storage_file, 'r') as f:
            data = json.load(f)
        if data['expires'] < now:
            raise ValueError('time expired')
        else:
            return data[key]
    except:
        try:
            r = requests.get(url)
        except:
            return None
        data = r.json()
        data['expires'] = time.time() + data['expires_in'] - 10*60
        if not os.path.exists(os.path.dirname(storage_file)):
            os.makedirs(os.path.dirname(storage_file))
        with open(storage_file, 'w+') as f:
            json.dump(data, f)
        return data[key]


def get_access_token():
    url = "https://api.weixin.qq.com/cgi-bin/token" + \
          "?grant_type=client_credential&appid=%s&secret=%s" % (APP_ID, APP_SECRET)
    return get_token(url, ACCESS_TOKEN_FILE, 'access_token')

def get_jsapi_ticket():
    access_token = get_access_token()
    url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket" + \
          "?access_token=%s&type=jsapi" % (access_token)
    return get_token(url, JSAPI_TICKET_FILE, 'ticket')

def get_jsapi_signature(url):
    now = int(time.time())
    ticket = get_jsapi_ticket()
    if ticket is None:
        return None
    data = {
        'noncestr': NONCESTR,
        'jsapi_ticket': ticket,
        'timestamp': now,
        'url': url
    }
    signature_str = ""
    for key, val in sorted(data.iteritems()):
        signature_str += "%s=%s&" % (key.lower(), val)
    signature_str = signature_str[:-1]
    signature = hashlib.sha1(signature_str).hexdigest()
    return {
        'signature': signature,
        'appId': APP_ID,
        'timestamp': now,
        'nonceStr': NONCESTR
    }

def save_image(file_type, file_dir, content):
    file_name = "%s.%s" % (uuid.uuid4(), file_type)
    file_path = os.path.join(BASE_DIR,'wechat/media', file_dir, file_name)
    if not os.path.exists(os.path.dirname(file_path)):
            os.makedirs(os.path.dirname(file_path))
    with open(file_path, 'wb') as f:
        f.write(content)
    relative_path = os.path.join('/media', file_dir, file_name)
    return re.sub(r'\\', r'/', relative_path)

def save_data(data):
    if not os.path.exists(os.path.dirname(DATA_STORAGE_FILE)):
        os.makedirs(os.path.dirname(DATA_STORAGE_FILE))
    with codecs.open(DATA_STORAGE_FILE, 'w+', encoding='utf8') as f:
        json.dump(data, f)

def get_data():
    try:
        with open(DATA_STORAGE_FILE, 'r') as f:
            return json.load(f)
    except:
        return {
            'money': 0,
            'people': 0,
            'year': 2015,
            'month': 5,
            'day': 20
        }